# coding=utf-8
import os
import configparser

import re
from flask import json

from core.storeinfo import StoreInfo
from core.users import Users
from tools import md5, convert
from tools.OperationError import OperationError
from tools.httpdoer import Request
from tools.properties import PropertiesUtils
from webapp.config import Config


class CpuRegist:
    def cpuRegist(self, cpu, name, password, isUsername='N', isPassword='N'):

        try:
            # 在线模式
            print("cpuRegist cpu:" + str(cpu))
            request = Request(Config.ERP_URL + "api/pos/cpuRegist")
            request.method = "post"  # 调用 _set_method
            request.timeout = 10  # 调用 _set_timeout
            request.path_params = None
            request.query = {"CPU": cpu, "NAME": name, "PASSWORD": password}
            r = request.send(json=False)

            if r is None:
                raise OperationError(-1, "服务端没有返回数据")
            else:
                # 处理数据并返回
                self.setInfo(r, name, password, isUsername, isPassword)
        except BaseException as e:
            # 在线报错是否抛出，由后期设计决定，暂时不抛出
            if type(e) != OperationError:
                raise e

        # 获取本地信息
        res = self.getInfo()
        if res == None or res == {}:
            raise OperationError(-1, "数据为空")

        return res

    def setInfo(self, response, name, password, isUsername='N', isPassword='N'):

        print(response.text)

        if response.status_code != 200:
            raise OperationError(-1, "服务端请求失败", response.text)

        if response.json == None:
            raise OperationError(-1, "服务器返回格式错误")  # print(type(res))

        res = convert.to_dict(response.json)  # print(type(res))
        if res["code"] == 0:
            # message = res["message"]
            r_data = res.get("data", None)
            if r_data == None or len(r_data) <= 0:
                raise OperationError(-1, "没有激活店仓的记录")
            print(r_data)
            arr = r_data
            # 保存店仓信息
            storeInfo = StoreInfo()
            storeInfo.saveStoreInfo(arr)
            # 是否记住账号密码
            users = Users()
            users.saveUserRemInfo(name, password, isUsername, isPassword)

        # 保存返回信息
        self.saveInfo(res)

    def saveInfo(self, res):
        if len(res) > 0:
            # 获取路径
            filename = Config.ROOT_PATH + os.sep + r"initconfig" + os.sep + "master.properties"
            PropertiesUtils().saveProperties(filename, Config.KEY_CUPREGIST, res)

    def getInfo(self):
        filename = Config.ROOT_PATH + os.sep + r"initconfig" + os.sep + "master.properties"
        print(filename)
        res = PropertiesUtils().getProperties(filename, Config.KEY_CUPREGIST)
        return res


if __name__ == "__main__":
    passwordMd5 = md5.genearteMD5("FCPOS01")
    cpuRegist = CpuRegist()
    r = cpuRegist.cpuRegist("cs004", "FCPOS01", passwordMd5)
    print(r)

    # store = StoreInfo()
    # storeinfo = store.getStoreInfo()
    # print(storeinfo)
    # cpuRegist.getStoreInfo();
